package io.github.weiranyi;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

/**
 * 秒杀案例
 * redis保存数据信息：
 * 1）商品库存：
 * key-> sk:proid:kc
 * string-> 剩余个数(库存)
 * 2）秒杀成功者：
 * key-> sk:prod-id:usr
 * set-> 成功者user_id1,成功者user_id2······
 */
public class SecKillServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1.随机生成用户的id;每个用户只能秒杀一次（实际中应该从session中获取userId）
        String userid = new Random().nextInt(5000) + "";
        // 2.获取要秒杀的商品id
        String prodid = request.getParameter("prodid"); //0101
        // 3.执行秒杀，存在超卖问题
//        String result = SecKill2.doSecKill(userid, prodid);
        boolean result = SecKill3.doSecKill(userid, prodid);
        // 4.返回提示信息
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(result);
    }
}
